package com.sk.weichat.adapter;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.ChatMessageEntity;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.message.ChatOverviewActivity;
import com.sk.weichat.util.DateUtils;
import com.sk.weichat.util.FileUtil;
import com.sk.weichat.video.ChatVideoPreviewActivity;
import com.sk.weichat.view.pictureviewer.ImagePagerActivity;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ImageVideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<ChatMessage> mChatMessageSource;

    private List<ChatMessageEntity> chatMessageEntities;
    private Context context;

    public ImageVideoAdapter(Context context, List<ChatMessageEntity> chatMessageEntities, List<ChatMessage> chatMessages) {
        this.mChatMessageSource = chatMessages;
        this.chatMessageEntities = chatMessageEntities;
        if (mChatMessageSource == null) {
            mChatMessageSource = new ArrayList<>();
        }
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ImageVideoHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_image_video, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        ChatMessage chatMessage = mChatMessageSource.get(position);
        boolean isExist = false;
        if (!TextUtils.isEmpty(chatMessage.getFilePath()) && FileUtil.isExist(chatMessage.getFilePath())) {
            isExist = true;
        }
        if (chatMessage.getType() == XmppMessage.TYPE_IMAGE) {
            ((ImageVideoHolder) viewHolder).mVideoIv.setVisibility(View.GONE);
            ((ImageVideoHolder) viewHolder).video_total_time.setVisibility(View.GONE);
            Glide.with(context).load(isExist ? new File(chatMessage.getFilePath()) : chatMessage.getContent()).error(R.drawable.image_download_fail_icon).into((((ImageVideoHolder) viewHolder).mIv));
        } else {
            ((ImageVideoHolder) viewHolder).mVideoIv.setVisibility(View.GONE);
            ((ImageVideoHolder) viewHolder).video_total_time.setVisibility(View.VISIBLE);
            if (isExist) {
                AvatarHelper.getInstance().displayVideoThumb(chatMessage.getFilePath(), (((ImageVideoHolder) viewHolder).mIv));
            } else {
                AvatarHelper.getInstance().asyncDisplayOnlineVideoThumb(chatMessage.getContent(), (((ImageVideoHolder) viewHolder).mIv));
            }
            try {
                MediaPlayer mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(chatMessage.getFilePath());
                mediaPlayer.prepare();
                int time = mediaPlayer.getDuration();//获得了视频的时长（以毫秒为单位）
                ((ImageVideoHolder) viewHolder).video_total_time.setText(DateUtils.stringForTime(time));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ((ImageVideoHolder) viewHolder).mContentRl.setOnClickListener(v -> {
            if (chatMessage.getType() == XmppMessage.TYPE_IMAGE) {
                List<String> url = new ArrayList<>();
                int imageChatMessageList_current_position = 0;


                for (int i = 0; i < mChatMessageSource.size(); i++) {
                    if (mChatMessageSource.get(i).getPacketId().equals(chatMessage.getPacketId())) {
                        imageChatMessageList_current_position = i;
                    }
                    url.add(mChatMessageSource.get(i).getContent());
                }

                Intent intent = new Intent(context, ImagePagerActivity.class);
                // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) url);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, imageChatMessageList_current_position);
//                Intent intent = new Intent(context, ChatOverviewActivity.class);
//                intent.putExtra("imageChatMessageList", JSON.toJSONString(mChatMessageSource));
//                intent.putExtra("imageChatMessageList_current_position", imageChatMessageList_current_position);
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(context, ChatVideoPreviewActivity.class);
                intent.putExtra(AppConstant.EXTRA_VIDEO_FILE_PATH, (!TextUtils.isEmpty(chatMessage.getFilePath()) && FileUtil.isExist(chatMessage.getFilePath())) ?
                        chatMessage.getFilePath() : chatMessage.getContent());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mChatMessageSource.size();
    }

    class ImageVideoHolder extends RecyclerView.ViewHolder {

        private RelativeLayout mContentRl;
        private ImageView mIv, mVideoIv;
        private TextView video_total_time;

        public ImageVideoHolder(@NonNull View itemView) {
            super(itemView);
            mContentRl = itemView.findViewById(R.id.content_rl);
            mIv = itemView.findViewById(R.id.iv);
            mVideoIv = itemView.findViewById(R.id.video_iv);
            video_total_time = itemView.findViewById(R.id.video_total_time);
        }
    }

}

